package self.hoy.demo.cloud.service;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

@Service
@DefaultProperties(defaultFallback = "globalFallBackHandler")
public class PaymentService {
    public String sayHello(Integer id) {
        return "线程池: " + Thread.currentThread().getName()
                + " is saying hello, id : " + id + "\t" + " O(n_n)O";
    }

    @HystrixCommand(
            fallbackMethod = "timeOutHandler",
            commandProperties = {
                    @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "4000")
            })
    public String timeOutHello(Integer id) {
        try {
            Thread.sleep(id * 100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "线程池: " + Thread.currentThread().getName()
                + " is timeout, id : " + id + "\t" + " O(T-T)O";
    }

    public String timeOutHandler(Integer id) {
        return "/(T o T)/调用支付接口超时或异常 in thread : \t" + Thread.currentThread().getName();
    }

    public String globalFallBackHandler(){
        return "(╥╯^╰╥) in thread : \t" + Thread.currentThread().getName();
    }

    @HystrixCommand(
            fallbackMethod = "paymentCircuitBreakerFallBack",
            commandProperties = {
                @HystrixProperty(name="circuitBreaker.enabled", value = "true"),
                @HystrixProperty(name="circuitBreaker.requestVolumeThreshold", value = "10"),
                @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
                @HystrixProperty(name="circuitBreaker.errorThresholdPercentage", value = "60")
    })
    public String paymentCircuitBreaker(@PathVariable("id")Integer id) {
        if (id == null || id % 2 == 1) {
            throw new RuntimeException("id 只能是偶数！");
        }
        String serialNum = IdUtil.simpleUUID();
        return Thread.currentThread().getName() + "\t 调用成功，流水号：" + serialNum;
    }

    public String paymentCircuitBreakerFallBack(@PathVariable("id")Integer id) {
        return "id 只能是偶数";
    }
}
